package com.atguigu.zy.interview.bug.test;

import java.util.concurrent.TimeUnit;

/**
 *  资源
 */
class MyHoldLockThread implements Runnable{
    private String lockA;
    private String lockB;

    public MyHoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }
    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+"\t 自己持有：\t"+lockA+"\t 尝试获得：\t"+lockB);

            //@formatter:off  线程暂停一会儿
            try { TimeUnit.SECONDS.sleep( 2 ); } catch (InterruptedException e) { e.printStackTrace();}
            //@formatter:on
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+"\t 自己持有：\t"+lockB+"\t 尝试获得：\t"+lockA);
            }
        }

    }
}

/**
 * @author Jungle
 * @create 2023-09-02 19:07
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(() -> {
           new MyHoldLockThread(lockA, lockB);
        }, "threadAAA").start();

        new Thread(new MyHoldLockThread(lockA, lockB),"threadAAA").start();

        new Thread(new MyHoldLockThread(lockB, lockA),"threadBBB").start();
    }
}
